<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-time Heart Chart with D3.js</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
  <style>
    /* 添加样式以美化心电图 */
    path {
      fill: none;
      stroke: red;
      stroke-width: 2;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas"></canvas>

<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // 创建动态数据
  var data = [];
  for (var i = 0; i < 100; i++) {
    data.push(Math.random());
  }

  function draw() {
    // 清除画布
    context.clearRect(0, 0, canvas.width, canvas.height);

    // 创建比例尺
    var xScale = d3.scaleLinear()
      .domain([0, data.length - 1])
      .range([0, canvas.width]);

    var yScale = d3.scaleLinear()
      .domain([0, 1])
      .range([canvas.height, 0]);

    // 画线
    context.beginPath();
    context.moveTo(xScale(0), yScale(data[0]));

    for (var i = 1; i < data.length; i++) {
      context.lineTo(xScale(i), yScale(data[i]));
    }

    context.lineWidth = 2;
    context.strokeStyle = "blue";
    context.stroke();

    // 更新数据
    data.shift();
    data.push(Math.random());

    // 延迟调用绘图函数
    requestAnimationFrame(draw);
  }

  // 开始绘图
  draw();
</script>
</body>
</html>